<template>
    <el-form ref="form" class="p-range-detail-form" :model="form" :rules="rules">
        <el-collapse :value="['1', '2', '3', '4', '5']" class="detail-collapse">
            <!--general-->
            <el-collapse-item :title="$t('lang.general')" name="1">
                <el-form-item :label="$t('lang.id')" prop="id">
                    <v-text v-if="readonly || status !== 'add'" v-model="form.id" />
                    <el-input v-else v-model="form.id" size="small" />
                </el-form-item>
                <el-form-item :label="$t('lang.color')" prop="color">
                    <el-input v-if="!readonly" v-model="form.color" size="small" />
                    <el-color-picker v-model="form.color" :disabled="readonly" show-alpha />
                    <v-text v-if="readonly" v-model="form.color" :limit="15" />
                </el-form-item>
                <el-form-item :label="$t('lang.layer')" prop="layer">
                    <v-text v-if="readonly" v-model="form.layer" />
                    <el-select v-else v-model="form.layer" :placeholder="$t('lang.pleaseSelect')" size="small">
                        <el-option v-for="(val, idx) in layerOptions" :key="idx + 'idx'" :label="val" :value="val" />
                    </el-select>
                </el-form-item>
            </el-collapse-item>

            <el-collapse-item :title="$t('lang.label')" name="2">
                <!--label-->
                <el-form-item :label="$t('lang.text')" prop="label">
                    <v-text v-if="readonly" v-model="form.label" />
                    <el-input v-else v-model="form.label" size="small" />
                </el-form-item>
                <el-form-item :label="$t('lang.color')" prop="labelColor">
                    <el-input v-if="!readonly" v-model="form.labelColor" :disabled="labelDisabled" size="small" />
                    <el-color-picker v-model="form.labelColor" :disabled="readonly || labelDisabled" show-alpha />
                    <v-text v-if="readonly" v-model="form.labelColor" :limit="15" />
                </el-form-item>
                <el-form-item :label="$t('lang.offsetXY')" prop="labelOffset">
                    <template v-if="readonly">
                        <v-text :value="form.labelOffset.x + ' px | ' + form.labelOffset.y + ' px'" />
                    </template>
                    <template v-else>
                        <el-input v-model="form.labelOffset.x" :disabled="labelDisabled" size="small" />
                        <el-input v-model="form.labelOffset.y" :disabled="labelDisabled" size="small" />
                    </template>
                </el-form-item>
            </el-collapse-item>
            <!--layout-->
            <el-collapse-item v-if="!readonly" :title="$t('lang.layout')" name="3">
                <el-form-item :label="$t('lang.action')" prop="action">
                    <v-text v-if="readonly" v-model="form.actionExt"></v-text>
                    <el-select v-else v-model="form.actionExt" :placeholder="$t('lang.pleaseSelect')" size="small">
                        <el-option
                            v-for="(val, idx) in actionOptions"
                            :key="idx + 'action'"
                            :label="val.label"
                            :value="val.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="X[mm]" prop="actionXExt">
                    <v-text v-if="readonly" v-model="form.actionXExt"></v-text>
                    <el-input v-else :disabled="actionXDisabled" v-model="form.actionXExt" size="small"></el-input>
                </el-form-item>
                <el-form-item label="Y[mm]" prop="actionYExt">
                    <v-text v-if="readonly" v-model="form.actionYExt"></v-text>
                    <el-input v-else :disabled="actionYDisabled" v-model="form.actionYExt" size="small"></el-input>
                </el-form-item>
            </el-collapse-item>
            <!--points-->
            <el-collapse-item :title="$t('lang.points')" name="4">
                <v-table
                    ref="vTable"
                    class="p-model-points-detail"
                    v-model="form.pointsExt"
                    isActive
                    :columns="pointsColumns"
                    :readonly="readonly"
                ></v-table>
            </el-collapse-item>
            <!--properties-->
            <el-collapse-item :title="$t('lang.properties')" name="5">
                <v-table
                    ref="vTable"
                    class="p-model-properties-detail"
                    v-model="form.propertiesExt"
                    isActive
                    :columns="propertiesColumns"
                    :readonly="readonly"
                ></v-table>
            </el-collapse-item>
        </el-collapse>
        <!--buttons-->
        <p-detail-buttons :compact="compact" :submit-func="submit" :readonly="readonly"></p-detail-buttons>
    </el-form>
</template>

<script type="text/ecmascript-6">
import * as API from '../../../core/api.js';
import * as Chef from '../../../core/Chef.js';
import * as SYSTEM from '../../../core/SYSTEM.enum.js';
import * as enums from '../../../store/status-enums.js';
import bus from '../../../utils/Eventbus.js';
import vText from '../../../utils/v-text.vue';
import vTable from '../../../utils/v-table.vue';
import pDetailButtons from '../p-detail-buttons.vue';
import i18n from '../../../lang/index.js';
const $t = i18n.global.t;

export default {
    name: 'p-range-detail-form',
    components: { vText, vTable, pDetailButtons },
    props: {
        id: String,
        ids: Array,
        value: Object,
        status: String,
        compact: Boolean,
        readonly: Boolean
    },
    data () {
        return {
            form: { labelOffset: { x: 0, y: 0 } },
            rules: {
                id: [{ required: true, message: $t('lang.id') + ' ' + $t('lang.required'), trigger: 'blur' }]
            },
            // actionOptions: Object.values(SYSTEM.PAINTER_ACTIONS),
            layerOptions: SYSTEM.RANGE_LAYERS,
            actionOptions: SYSTEM.PAINTER_ACTIONS_OPTIONS,
            propertiesColumns: [
                { label: 'name', prop: 'key', width: 180 },
                { label: 'value', prop: 'val', width: 120 }
            ],
            pointsColumns: [
                { label: 'x', prop: 'x', width: 180 },
                { label: 'y', prop: 'y', width: 120 }
            ],
            locals: null
        };
    },
    computed: {
        labelDisabled() {
            return !this.form.label;
        },
        actionDisabled() {
            return this.form.actionExt === SYSTEM.PAINTER_ACTIONS.NONE;
        },
        actionXDisabled() {
            return this.actionDisabled || this.form.actionExt === SYSTEM.PAINTER_ACTIONS.MIRRORY;
        },
        actionYDisabled() {
            return this.actionDisabled || this.form.actionExt === SYSTEM.PAINTER_ACTIONS.MIRRORX;
        }
    },
    watch: {
        // id: { handler () { this.init(); }, deep: true },
        // ids: { handler () { this.init(); }, deep: true },
        ids() { this.init(); },
        value: { handler (val) { this.form = val; }, deep: true },
        form (val) {
            this.$emit('input', val);
        }
    },
    created() {
        // 图形不能没有翻转的选项 2020-05-06 slq
        this.actionOptions.map((item, idx) => {
            if (item.value === SYSTEM.PAINTER_ACTIONS.REVERSE) this.actionOptions.splice(idx, 1);
        });
        bus.on(`rangesEditor.init`, this.init);
    },
    mounted() {
        this.init();
    },
    beforeDestroy() {
        bus.off(`rangesEditor.init`, this.init);
    },
    methods: {
        init(locals) {
            console.log('p-range-detail-form.init: ', locals, this.ids, ...arguments);
            if ((locals && locals.length) || (this.locals && this.locals.length)) {
                if (locals) {
                    locals.forEach(v => v.id = '-1');
                    this.locals = locals;
                }
                let form = Chef.combineRanges(this.locals);
                Chef.extendRange(form);
                this.form = form;
                if (this.compact && this.form.propertiesExt && this.form.propertiesExt.length < 1) this.form.propertiesExt = [['', '']];
            } else if (this.ids.length && this.ids.toString() !== '-1') {
                this.getDetails(this.ids).then(res => {
                    Chef.extendRange(res);
                    this.form = res;
                    if (this.compact && this.form.propertiesExt && this.form.propertiesExt.length < 1) this.form.propertiesExt = [['', '']];
                });
            } else this.form = { labelOffset: { x: 0, y: 0 } };
        },
        getDetails(ids) {
            console.log('p-range-detail-form.getDetails: ', ids);
            return API.filterLocalResources('ranges', ids).then(res => {
                return Chef.combineRanges(res.list);
            });
        },
        validate(vehicleErrors = false) {
            if (vehicleErrors) {
                this.$refs.vTable.$children.concat().map(o => o.$el.classList.remove('error'));
                Object.keys(this.$validation).forEach(k => {
                    if (Object.keys(this.$validation[k]).length) {
                        let e = this.$refs.vTable.$children.concat().find(c => c._uid === parseInt(k));
                        e.$el.classList.add('error');
                    }
                });
            }
            for (let key in this.$validation) {
                if (this.$validation.hasOwnProperty(key)) {
                    for (let k in this.$validation[key]) {
                        if (this.$validation[key].hasOwnProperty(k)) {
                            this.$toast(this.$validation[key][k]);
                            return false;
                        }
                    }
                }
            }
            return true;
        },
        execActions(forms) {
            if (!this.form.actionExt) return forms;
            forms.forEach(f => {
                if (this.form.actionExt === SYSTEM.PAINTER_ACTIONS.MOVE) {
                    f.points.forEach(p => {
                        p.x = Number(p.x) + Number(this.form.actionXExt || 0);
                        p.y = Number(p.y) + Number(this.form.actionYExt || 0);
                    });
                } else if (this.form.actionExt === SYSTEM.PAINTER_ACTIONS.MIRRORX) {
                    f.points.forEach(p => {
                        p.x = Number(this.form.actionXExt || 0) * 2 - p.x;
                    });
                } else if (this.form.actionExt === SYSTEM.PAINTER_ACTIONS.MIRRORY) {
                    f.points.forEach(p => {
                        p.y = Number(this.form.actionYExt || 0) * 2 - p.y;
                    });
                }
            });
            return forms;
        },
        submit(e) {
            // v-table 里面没有必填项 所以this.validate无需校验了
            // if (!this.validate(true)) return Promise.reject('');
            return this.$refs.form.validate().then(valid => {
                if (valid) {
                    let form = Chef.shakeRange(this.form);
                    let list = [];
                    if (this.locals && this.locals.length) list = this.locals;
                    else list = this.$root.resources.ranges.filter(v => this.ids.indexOf(v.id) >= 0);
                    console.log('p-range-detail-form.submit: ', list);
                    let forms = Chef.separateRanges(list, form);
                    console.log('p-range-detail-form.submit: ', forms, form);
                    if (!forms || !forms.length) return Promise.reject();
                    forms = this.execActions(forms);
                    console.log('p-range-detail-form.submit: ', this.form, forms);
                    return API.updateRanges(forms, e.target || e.srcElement).then(res => {
                        if (this.locals && this.locals.length) this.locals = null;
                        console.log('p-range-detail-form.submit.success: ', res);
                        bus.emit('p-table.init');
                        bus.emit('p-painter.clearLocals');
                        this.$store.commit(enums.DESELECT_RANGES_ALL);
                        // 关闭点亮状态
                        this.$store.commit(enums.DEACTIVE_DRAW_RANGES);
                        bus.emit('ranges.toggleRowSelection', []);
                        if (this.compact) {
                            bus.emit('p-panel.editEnableChange', false);
                            bus.emit('ranges.toggleRowSelection', []);
                        }
                    });
                } else {
                    let msg = $t('lang.submitError');
                    this.$message.error(msg);
                    return Promise.reject(msg);
                }
            });
        }
    }
};
</script>

<style lang="scss">
.page-range-detail-form {
}
</style>
